package com.mego.tzadd.activitys;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.mego.tzadd.R;
import com.mego.tzadd.database.manager.SystemCenter;
import com.mego.tzadd.utils.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.BottomMenuWindow;

//连接wifi
//https://blog.csdn.net/wangyongyao1989/article/details/83584605
public class LjwifiActivity extends BaseActivity implements View.OnClickListener, AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {

    private final String TAG = "LjwifiActivity";

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    public static Intent createIntent(Context context) {
        return new Intent(context, LjwifiActivity.class);
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ljwifi_activity);

        initView();
        initData();
        initEvent();

        isLocServiceEnable(this);
    }

    public boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        showShortToast("搜尋WIFI，請開啟位置服務！");

        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, 213);
        return false;
    }

    @Override
    public void initData() {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }


    @Override
    public void onForwardClick(View v) {

    }

    private TextView tv_ljinfo;
    private TextView tv_ljinfo2;
    private TextView tv_next;
    private TextView tv_selectwifi;

    @Override
    public void initView() {
        ImageButton ivBaseTabReturn = (ImageButton) findViewById(R.id.ivBaseTabReturn);
        if (ivBaseTabReturn != null) {
            ivBaseTabReturn.setScaleType(ImageView.ScaleType.FIT_START);
        }

        tv_ljinfo = (TextView) findViewById(R.id.tv_ljinfo);
        tv_ljinfo2 = (TextView) findViewById(R.id.tv_ljinfo2);
        tv_next = (TextView) findViewById(R.id.tv_next);
        tv_selectwifi = (TextView) findViewById(R.id.tv_selectwifi);


    }


    @Override
    public void initEvent() {

        findViewById(R.id.tv_sdlj).setOnClickListener(this);
        findViewById(R.id.tv_next).setOnClickListener(this);
        findViewById(R.id.tv_saveselectwifissid).setOnClickListener(this);

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);

        onSavewifi();

    }

    String _ssid = "";//目标ssid
    WifiManager wifiManager = null;

    int _conectnum = 0;//累计连接次数

    void tryconnect() {
        if (_conectnum > 2) {
            return;
        }
        tv_ljinfo.setText("正在連接裝置：" + _ssid);
        showProgressDialog("開始連接Wi-Fi " + _ssid);
        _conectnum++;
        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送数据
                try {
                    Thread.sleep(2000);
                    mHandler.sendEmptyMessage(STARTLINKWIFI);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public boolean connect(@NonNull String ssid) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";
        config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        int networkID = wifiManager.addNetwork(config);

        boolean result = wifiManager.enableNetwork(networkID, true);
        return result;
    }

    private WifiInfo wifiInfo;
    private DhcpInfo dhcpInfo;

    private String _gatewayIP = "192.168.4.1"; //机台网关

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_saveselectwifissid:
                onSavewifi();
                showShortToast("已記錄！");
                break;
            case R.id.tv_sdlj:
                onSdlj();//連接裝置
                break;
            case R.id.tv_next:
                onNext();
                break;

        }
    }

    private void onSavewifi() {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        String ssid = wifiInfo.getSSID();
        ssid = ssid.replace("\"", "");
        SystemCenter.getInstance().ssid0 = ssid;
        tv_selectwifi.setText("WI-FI: " + SystemCenter.getInstance().ssid0);
    }

    private String intToIp(int paramInt) {
        return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
                + (0xFF & paramInt >> 24);
    }

    void onNext() {
        if (!_candonext) {
            return;
        }
        dhcpInfo = wifiManager.getDhcpInfo();
        wifiInfo = wifiManager.getConnectionInfo();
        String strWifiinfo = "SSID：" + wifiInfo.getSSID() + "IpAddress：" + intToIp(wifiInfo.getIpAddress()) + " MacAddress：" + wifiInfo.getMacAddress();

        if (wifiInfo.getSSID().contains("AI-") || wifiInfo.getSSID().contains("DF-")) {

        } else {
            showShortToast("尚未連接到裝置WIFI，無法進行下一步!");
            _candonext = false;
            return;
        }

        _gatewayIP = intToIp(dhcpInfo.gateway);
        if (intToIp(dhcpInfo.gateway).compareToIgnoreCase("192.168.4.1") != 0) {
            showShortToast("裝置網關錯誤! " + intToIp(dhcpInfo.gateway));
            _candonext = false;
            return;
        }

        if (ct != null) {
            ct.interrupt();
            ct = null;
        }

        SystemCenter.getInstance().ssid = wifiInfo.getSSID();
        startActivityForResult(XzwifiActivity.createIntent(this), REQUEST_TO_LJWIFI);
//        startActivity(XzwifiActivity.createIntent(this));
//        finish();
    }

    List<ScanResult> _wifilist;
    ArrayList<String> _ssidList = new ArrayList<String>();

    private void onSdlj() {
        Intent intent = new Intent();
        intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
        startActivity(intent);
    }

    private final int REQUEST_TO_BOTTOM_MENU_0 = 31;
    private final int REQUEST_TO_LJWIFI = 36;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == REQUEST_TO_LJWIFI) {
            setResult(RESULT_OK);
            finish();
            return;
        }

        switch (requestCode) {
            case REQUEST_TO_BOTTOM_MENU_0:
                if (data != null) {
                    int selectedPosition = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (selectedPosition >= 0 && selectedPosition < _ssidList.size()) {
                        _ssid = _ssidList.get(selectedPosition);
                        _conectnum = 1;
                        tryconnect();
                    }
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        _candonext = false;
        tv_next.setTextColor(Color.parseColor("#666666"));
        TimeRefresher.getInstance().addTimeRefreshListener(TAG, 1000, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);

        if (ct != null) {
            ct.interrupt();
            ct = null;
            return;
        }
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }

    public static final int STARTLINKWIFI = 608;
    public static final int FINISHTRYLINK_OK = 609;
    public static final int FINISHTRYLINK_ERR = 610;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == STARTLINKWIFI) {
                dismissProgressDialog();
                if (!connect(_ssid)) {
                    showShortToast("連接Wi-Fi失敗 " + _ssid);
                    tv_ljinfo.setText("自動連線失敗!");
                    tv_ljinfo2.setText("");
                }
            } else if (FINISHTRYLINK_OK == msg.what) {
                tv_next.setTextColor(Color.parseColor("#FFFFFFFF"));
                _candonext = true;
                _islinking = false;
            } else if (FINISHTRYLINK_ERR == msg.what) {
                _candonext = false;
                _islinking = false;
                tv_next.setTextColor(Color.parseColor("#666666"));
            }
        }
    };


    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }
    }


    @Override
    public void onTimerStart() {

    }

    boolean _candonext = false;

    @Override
    public void onTimerRefresh() {
        if (!_candonext) {
            wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo.getSSID().contains("AI-") || wifiInfo.getSSID().contains("DF-")) {
                trylink();
            }
        }
    }

    private ConnectThread ct = null;
    boolean _islinking = false;

    void trylink() {
        if (_islinking) {
            return;
        }
        _islinking = true;
        dhcpInfo = wifiManager.getDhcpInfo();
        wifiInfo = wifiManager.getConnectionInfo();
        _gatewayIP = intToIp(dhcpInfo.gateway);
        if (intToIp(dhcpInfo.gateway).compareToIgnoreCase("192.168.4.1") != 0) {
            _islinking = false;
            return;
        }
//        if (ct != null) {
//            ct.interrupt();
//            ct = null;
//        }
//        ct = new ConnectThread();
//        ct.start();
        mHandler.sendEmptyMessage(FINISHTRYLINK_OK);
    }

    @Override
    public void onTimerStop() {

    }

    class ConnectThread extends Thread {
        public Socket socket = null;        //定义socket
        public OutputStream outputStream = null;    //定义输出流（发送）
        public InputStream inputStream = null;    //定义输入流（接收）

        public void run() {
            socket = null;
            try {
                socket = new Socket(_gatewayIP, 8080);
//                socket = new Socket("192.168.31.139", 8901);
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (socket == null) {
                mHandler.sendEmptyMessage(FINISHTRYLINK_ERR);
                return;
            }

            mHandler.sendEmptyMessage(FINISHTRYLINK_OK);

        }
    }

}

